import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { ValidationPipe } from '@nestjs/common';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
import { Reflector } from '@nestjs/core';
import { fixWorkspaceStatus } from './config/fix-workspace-status';

async function bootstrap() {
  // 先运行修复脚本
  // if (process.env.NODE_ENV !== 'production') {
  //   try {
  //     await fixWorkspaceStatus();
  //     console.log('数据库修复完成，继续启动应用');
  //   } catch (error) {
  //     console.error('数据库修复失败，但将继续尝试启动应用', error);
  //   }
  // }

  const app = await NestFactory.create(AppModule, {
    logger: ['error', 'warn', 'debug', 'log', 'verbose'], // 启用所有日志级别
  });
  
  // 添加全局验证管道
  app.useGlobalPipes(new ValidationPipe({
    transform: true,
    whitelist: true,
  }));
  
  // 配置 CORS
  app.enableCors();
  
  // 配置全局 JWT 认证守卫
  const reflector = app.get(Reflector);
  app.useGlobalGuards(new JwtAuthGuard(reflector));
  
  // 配置 Swagger 文档
  const config = new DocumentBuilder()
    .setTitle('Monday API')
    .setDescription('Monday 项目管理系统 API 文档')
    .setVersion('1.0')
    .addBearerAuth()
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);
  
  const port = process.env.PORT || 3000;
  await app.listen(port);
  console.log(`应用已启动: http://localhost:${port}`);
  console.log(`Swagger 文档: http://localhost:${port}/api`);
}
bootstrap();
